import router from './router/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from "../src/store/modules/user"
import { usePermissionStore } from "../src/store/modules/permission"
import { ElMessage, ElMessageBox } from "element-plus";
import { closeWebSocket } from '../src/utils/socket';
import * as _ from 'lodash'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login/index', '/login/roles', '/login/forget', '/login/resuccess', '/login/register', '/auth-redirect'] // 设置白名单
// 记录路由
let hasRoles = true
// 过期提醒
const returnTip = _.debounce((tip) => {
    closeWebSocket()
    ElMessageBox.confirm(tip, '温馨提示', {
        confirmButtonText: '确定',
        type: 'error',
        showCancelButton: false,
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
    }).then(() => {
        const UserStore = useUserStore()
        UserStore.token = null
        UserStore.roles = []
        UserStore.row = {
            tokenValue: null, //登录token
            expireIn: null, //过期时间
            tokenStartTime: null, //登录当前时间
            refreshToken: null, //刷新token
            tokenName: null,
        }
        window.localStorage.removeItem('ddfUserStat')
        usePermissionStore().clearRoutes()
        router.push({ path: '/login/index' })
    })
}, 10)
router.beforeEach(async (to, from, next) => {
    const UserStore = useUserStore();
    //判断是登录则关闭连接删除登录记录token
    if (to.path == '/login/index') {
        closeWebSocket()
        window.localStorage.removeItem('ddfUserStat')
    }
    // 开启进度条
    NProgress.start()
    // 设置标题
    if (typeof (to.meta.title) === 'string') {
        document.title = to.meta.title || '智宝售后'
    }
    // 确定用户是否已登录过，存在Token
    const hasToken = UserStore.row.tokenValue
    const tokenStartTime = UserStore.row.tokenStartTime
    const timeOver = UserStore.row.expireIn * 1000
    let date = new Date().getTime()
    if (hasToken) {
        if (date - tokenStartTime > timeOver) {
            returnTip('登录状态过期，请重新登录')
            return next('/login/index')
        } else {
            if (to.path === '/login/index') {
                if (!UserStore.token) {
                    next()
                } else {
                    next({ path: '/' })
                }
                // 如果已登录，请重定向到主页
            } else {
                try {
                    const PermissionStore = usePermissionStore()
                    // 路由添加进去了没有及时更新 需要重新进去一次拦截
                    if (!PermissionStore.routes.length) {
                        // 获取权限列表进行接口访问 因为这里页面要切换权限
                        const accessRoutes = await PermissionStore.generateRoutes(UserStore.roles)
                        hasRoles = false
                        if (Array.isArray(accessRoutes)) {
                            accessRoutes.forEach(item => router.addRoute(item)) // 动态添加访问路由表
                        }
                        next({ ...to, replace: true }) // // 这里相当于push到一个页面 不在进入路由拦截
                    } else {
                        next()  // 如果不传参数就会重新执行路由拦截，重新进到这里
                    }
                } catch (error) {
                    next('/login/index')
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login/index')
        }
    }
})

router.afterEach(() => {
    NProgress.done();
});


